package com.taotao.search.rabbit;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.search.pojo.Item;
import com.taotao.service.ItemService;

public class ItemListener {
	
	private static final ObjectMapper MAPPER = new ObjectMapper();
	
	@Autowired
	private HttpSolrServer solrServer;
	
	@Autowired
	private ItemService itemService;

	public void listen(String msg) throws IOException, SolrServerException{
		// 解析消息内容
		// 获取商品的id
		Long itemId = 0l;
		// 获取消息中的routingKey
		String routingKey = "";
		try {
			JsonNode jsonNode = MAPPER.readTree(msg);
			itemId = jsonNode.get("id").asLong();
			routingKey = jsonNode.get("routingKey").asText();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 判断操作类型
		if(StringUtils.equals("insert", routingKey) || StringUtils.equals("update", routingKey)){
			Item item = this.itemService.queryItemById(itemId);
			this.solrServer.addBean(item);
			this.solrServer.commit();
		} else if(StringUtils.equals("delete", routingKey)){
			this.solrServer.deleteById(itemId.toString());
			this.solrServer.commit();
		}
	}
}
